package com.strongwell.awe.service.impl;

import com.strongwell.awe.dao.WxTokenDao;
import com.strongwell.awe.model.WxTokenEntity;
import com.strongwell.awe.service.WxTokenService;
import com.strongwell.awe.util.WeChatUtil;
import org.apache.commons.httpclient.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

@Service("wxTokenServiceImpl")
public class WxTokenServiceImpl implements WxTokenService {
    public static final String mAppID = "wxce015f87a6b073c6";
    public static final String mAppSceret = "86988cf86b45b3a9477c2d005a6aaefa";

    @Autowired
    private WxTokenDao wxTokenDao;

    @Override
    public WxTokenEntity selectLatestOne(String appid, String appsecret) {
        return wxTokenDao.selectLatestOne(appid,appsecret);
    }

    @Override
    public void insert(WxTokenEntity wxTokenEntity) {
        Date date = new Date();
        Timestamp time = new Timestamp(date.getTime());
        wxTokenEntity.setCreatetime(time);
        wxTokenDao.insert(wxTokenEntity);
    }

    public WxTokenEntity getToken()
    {
        // 1.确定是否要更新token，无需更新则直接直接返回获取的token
        if (updateToken() != null)
        {
            return updateToken();
        }

        // 2. 如需更新
        if (!getTokenbyhttps(mAppID, mAppSceret))
        {
            System.out.println("获取失败！");
            return null;
        }

        return updateToken();
    }

    /**
     * 获取Token信息
     * @return
     */
    private WxTokenEntity updateToken(){
        WxTokenEntity wxTokenEntity = selectLatestOne(mAppID,mAppSceret);
        try {
            if(wxTokenEntity == null){
                System.out.println("未查询到对应的Token");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return wxTokenEntity;
    }

    private boolean getTokenbyhttps(String appID, String appSceret){
        Date date = new Date();
        Timestamp time = new Timestamp(date.getTime());
        WxTokenEntity entity = new WxTokenEntity();
        try
        {
            // 请求地址
            String path = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                    + appID + "&secret=" + appSceret;

            String strResp = WeChatUtil.doHttpsGet(path, "");


            // 解析获取的token信息
            Map<String, Object> tMap = WeChatUtil.jsonToMap(strResp);



            entity.setToken((String) tMap.get("access_token"));
            System.out.println(tMap.get("expires_in").getClass());
            entity.setExpires_in(Long.valueOf(tMap.get("expires_in").toString()));
            entity.setAppid(appID);
            entity.setAppsecret(appSceret);
            entity.setCreatetime(time);



        }
        catch (HttpException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        insert(entity);
        return true;
    }
}
